package org.roger.search;

import java.io.IOException;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.spatial.SpatialStrategy;
import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy;
import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree;
import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialOperation;

import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;

public class SpatialSearch extends LuceneSearchBase{
	
	//单位是千米
	private double dist;
	
	//原点
	private double lng;
	private double lat;
	
	public SpatialSearch(double lng,double lat,double dist){
		this.dist = dist;
		this.lng = lng;
		this.lat = lat;
	}
	

	@Override
	public Query getSearchQuery() {
		Term term = new Term("keyword","*饭店*");  
		WildcardQuery query = new WildcardQuery(term);
		return query;
	}

	@Override
	public Filter getFilter() {
		SpatialContext ctx = SpatialContext.GEO;
		int maxLevels = 11;
		
		SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
		SpatialStrategy strategy = new RecursivePrefixTreeStrategy(grid, "myGeoField");
		SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, ctx.makeCircle(lng,lat, DistanceUtils.dist2Degrees(dist,DistanceUtils.EARTH_MEAN_RADIUS_KM)));
		Filter filter = strategy.makeFilter(args);
		return filter;
	}

	@Override
	public Sort getSort() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public static void main(String[] args) {
		SpatialSearch search = new SpatialSearch(116.430459,39.939802,1.6);
		try {
			Long s1 = System.currentTimeMillis();
			search.search("D:/lucene/spatial");
			System.out.println("cost time:"+(System.currentTimeMillis()-s1));
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
